<?php

namespace app\admin\controller\xiluedu;

use app\admin\model\User;
use app\common\controller\Backend;
use app\admin\model\xiluedu\CouponCourse;
use app\admin\model\xiluedu\UserCoupon;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Coupon extends Backend
{
    protected $noNeedRight = ['send'];
    /**
     * Coupon模型对象
     * @var \app\admin\model\xiluedu\Coupon
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\xiluedu\Coupon;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("freightTypeList", $this->model->getFreightTypeList());
        $this->view->assign("rangeStatusList", $this->model->getRangeStatusList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $course_ids = $this->request->post("course_ids/a",null);
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if($course_ids){
                        $this->model->addCouponCourse($course_ids);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    $course_ids = $this->request->post("course_ids/a",null);
                    if($course_ids){
                        $row->addCouponCourse($course_ids);
                    }
                    if($params['range_status'] == '1'){
                        CouponCourse::where('coupon_id',$row->id)->delete();
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $course_ids = $row->range_status == '2' ? CouponCourse::where('coupon_id',$row->id)->column('course_id') : [];
        $course = !$course_ids?[] : \app\admin\model\xiluedu\Course::whereIn('id',$course_ids)->select();

        $this->view->assign("row", $row);
        $this->view->assign("course", $course? collection($course)->toArray() : []);
        return $this->view->fetch();
    }

    /**
     * 查看会员
     */
    public function users()
    {
        $this->model = new User();
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $coupon_id = $this->request->param('coupon_id');
        $this->view->assign('coupon_id',$coupon_id);
        $this->assignconfig('coupon_id',$coupon_id);
        return $this->view->fetch();
    }


    /**
     * 发放日志
     */
    public function user_coupons(){
        $this->model = new UserCoupon();
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['user'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
//            foreach ($list as $k => $v) {
//                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
//                $v->hidden(['password', 'salt']);
//            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 发放优惠券
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */

    public function send(){
        $type = $this->request->param('type','part');
        $coupon_id = $this->request->param('coupon_id');
        $user_ids = $this->request->param('user_ids');
        $logintime = $this->request->param('logintime');
        if(!$coupon_id) $this->error('参数错误');
        if($type == 'part' && !$user_ids) $this->error('参数错误');
        $coupon = $this->model->get($coupon_id);
        if(!$coupon){
            $this->error('优惠券不存在');
        }
        if($coupon['use_end_time']<time()){
            $this->error('优惠券已过期');
        }

        $where = ['status'=>'normal'];
        if($type == 'all'){
            if($logintime){
                $time = explode(' - ',$logintime);
                $where['logintime'] = ['between',[strtotime($time[0]),strtotime($time[1])]];
            }
            $users = User::where($where)->field('id,nickname')->select();
        }else{
            $users = User::where('id','in',$user_ids)->select();
        }
        if(!$users) {
            $this->error('未匹配到用户信息');
        }
        $user_coupon = [];
        foreach ($users as $user){
            $user_coupon[] = [
                'user_id' => $user['id'],
                'coupon_id'=>$coupon_id,
                'start_time'=> $coupon->use_start_time,
                'end_time'=> $coupon->use_end_time,
                'createtime'=>time(),
                'updatetime'=>time(),
            ];
        }
        try {
            $model =  new  \app\admin\model\xiluedu\UserCoupon();
            $model->saveAll($user_coupon);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('发放成功');
    }
}
